package com.hspedu.seckill.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hspedu.seckill.pojo.User;
import com.hspedu.seckill.service.UserService;
import com.hspedu.seckill.util.CookieUtil;
import com.hspedu.seckill.vo.RespBean;
import com.hspedu.seckill.vo.RespBeanEnum;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * AccessLimitInterceptor: 自定义拦截器
 */
@Component
public class AccessLimitInterceptor implements HandlerInterceptor {

    //装配需要的组件
    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 这个方法完成
     * 1. 得到user对象，并存入ThreadLocal
     * 2. 去处理@AccessLimit
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {
            //这里先获取到登陆的user对象
            User user = getUser(request, response);
            //存入到ThreadLocal
            UserContext.setUser(user);

            //把handler转成HandlerMethod
            HandlerMethod hm = (HandlerMethod) handler;
            //获得到目标方法的AccessLimit注解
            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
            if (null == accessLimit) {//如果目前方法没有AccessLimit注解，说明该接口并没有处理限流
                return true;//放行
            }
            //获得注解的值
            int second = accessLimit.second();//时间范围
            int maxCount = accessLimit.maxCount();//最大访问次数
            boolean needLogin = accessLimit.needLogin();//是否需要登录

            if (needLogin) {//说明用户必须登陆才能访问目标接口
                if (null == user) {//说明用户没有登陆
                    render(response,RespBeanEnum.SESSION_ERROR);
                    return false;
                }
            }

            String uri = request.getRequestURI();
            String key = uri + ":" + user.getId();

            Integer count = (Integer) redisTemplate.opsForValue().get(uri + ":" + user.getId());
            if (null == count) {//说明还没有这个key，就初始化值为1，过期时间为5秒
                redisTemplate.opsForValue().set(key, 1, second, TimeUnit.SECONDS);
            } else if (count < maxCount) {//说明正常访问
                redisTemplate.opsForValue().increment(key);
            } else {//说明用户在刷接口
                render(response,RespBeanEnum.ACCESS_LIMIT_REACHED);
                return false;
            }


        }

        return true;
    }

    //方法：构建返回对象，以流的形式返回
    private void render(HttpServletResponse response, RespBeanEnum respBeanEnum) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        //构建RespBean并转为字符串
        String error = new ObjectMapper().writeValueAsString(RespBean.error(respBeanEnum));
        out.print(error);
        out.flush();
        out.close();
    }


    //得到登陆的user对象，userTicket
    private User getUser(HttpServletRequest request, HttpServletResponse response) {
        String userTicket = CookieUtil.getCookieValue(request, "userTicket");
        if (!StringUtils.hasText(userTicket)) {
            return null;//说明用户没有登陆
        }
        return userService.getUserByCookie(userTicket, request, response);
    }


}
